using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using Sirenix.OdinInspector.Editor;
using Sirenix.Utilities.Editor;
using System.IO;

public class LevelEditorWindow : EditorWindow
{
    [MenuItem("Tools/LevelEditor")]
    static void Open()
    {
        GetWindow<LevelEditorWindow>();
    }
    public TileType tileType = TileType.Wall;
    public List<string> tileTypes = new List<string>();
    public Dictionary<TileType, List<GameObject>> tilePrefabs = new Dictionary<TileType, List<GameObject>>();
    public Transform tileParent;
    public Transform snapParent;
    // enable
    private void OnEnable()
    {
        SceneView.duringSceneGui += OnSceneGUI;
        tileTypes.Clear();
        foreach (var item in System.Enum.GetNames(typeof(TileType)))
        {
            tileTypes.Add(item);
        }
        SearchTilePrefab(Application.dataPath + "/Res");
        //gameobject find component
        var level = FindObjectOfType<Level>();
        if(level != null)
        {
            tileParent = level.transform;
        }else {
            tileParent = new GameObject("Level").transform;
            tileParent.gameObject.AddComponent<Level>();
        }

        var snap = FindObjectOfType<SnapToGridTest>();
        if(snap != null)
        {
            snapParent = snap.transform;
        }else {
            snapParent = new GameObject("Snap").transform;
            snapParent.gameObject.AddComponent<SnapToGridTest>();
        }
        
    }

    // disable
    private void OnDisable()
    {
        SceneView.duringSceneGui -= OnSceneGUI;
    }

    public enum OperatorType
    {
        None,
        Add,
        Delete,
        Move,
        Rotate,
        Scale,
    }

    public OperatorType operatorType = OperatorType.None;
    List<string> modes = new List<string>() { "None", "Add", "Delete", "Move", "Rotate", "Scale" };
    Vector2 scrollPos = Vector2.zero;

    // draw scene gui
    private void OnGUI()
    {
        // draw tileType toolbar
        GUILayout.BeginArea(new Rect(10, 10, 300, 50));
        GUILayout.BeginHorizontal();
        tileType = (TileType)GUILayout.Toolbar((int)tileType, tileTypes.ToArray());
        GUILayout.EndHorizontal();
        GUILayout.EndArea();
        GUILayout.Space(30);
        // draw scrollview 
        scrollPos = EditorGUILayout.BeginScrollView(scrollPos, GUILayout.Width(350), GUILayout.Height(100));
        EditorGUILayout.LabelField("LevelEditor");
        EditorGUILayout.EndScrollView();


    }

    // draw scene gui
    private void OnSceneGUI(SceneView sceneView)
    {
        // draw operator toolbar 
        Handles.BeginGUI();
        GUILayout.BeginArea(new Rect(60, 10, 600, 200));
        GUILayout.BeginHorizontal();
        //operator toolbar
        operatorType = (OperatorType)GUILayout.Toolbar((int)operatorType, modes.ToArray());
        GUILayout.EndHorizontal();
        GUILayout.EndArea();
        Handles.EndGUI();

        EventHandler();
        // sceneView.AlignViewToObject(tileParent);
        
    }

    void EventHandler()
    {
        HandleUtility.AddDefaultControl(GUIUtility.GetControlID(FocusType.Passive));
        Camera sceneCamera = SceneView.currentDrawingSceneView.camera;

        Vector3 mousePos = Event.current.mousePosition;
        // Vector3 worldPos = sceneCamera.ScreenToWorldPoint(mousePos);
        
        Vector3 worldPos = sceneCamera.ScreenToWorldPoint(new Vector3(mousePos.x, sceneCamera.pixelHeight - mousePos.y, sceneCamera.nearClipPlane));
        Debug.Log($"worldPos:{worldPos}");
        // Vector3 gridPos = WorldToGridCoordinates(worldPos);
        // Debug.Log($"worldPos:{worldPos}");
        // int col = (int)gridPos.x;
        // int row = (int)gridPos.z;
        // Debug.Log($"mousePos:{mousePos}");
        // Debug.LogFormat("GridPos {0},{1}", col, row);
        // Debug.Log(sceneCamera.transform.position);
        //lock scene camera
        var pos = new Vector3(worldPos.x, 0, worldPos.z);
        snapParent.position = pos;
    }

    // public Vector3 WorldToGridCoordinates(Vector3 point) {
    //     Vector3 gridPoint = new Vector3(
    //     (int)((point.x - tileParent.position.x) / 10),
    //     (int)((point.y - tileParent.position.y) / 10),
    //     (int)((point.z - tileParent.position.z) / 10));
    //     return gridPoint;
    // }

    //search directory and subdirectory with tile prefab
    public List<string> SearchTilePrefab(string path)
    {
        this.tilePrefabs.Clear();
        List<string> tilePrefabs = new List<string>();
        DirectoryInfo directoryInfo = new DirectoryInfo(path);
        FileInfo[] fileInfos = directoryInfo.GetFiles("*.prefab", SearchOption.AllDirectories);
        foreach (var item in fileInfos)
        {
            string filePath = item.FullName.Replace(@"\", "/");
            int index = filePath.IndexOf("Assets");
            string assetPath = filePath.Substring(index);
            // get component
            GameObject go = AssetDatabase.LoadAssetAtPath<GameObject>(assetPath);
            var comp = go.GetComponent<Tile>();
            if (comp != null)
            {
                tilePrefabs.Add(assetPath);
                if(!this.tilePrefabs.ContainsKey(comp.tileType))
                {
                    this.tilePrefabs.Add(comp.tileType, new List<GameObject>());
                }
                this.tilePrefabs[comp.tileType].Add(go);
            }
        }
        return tilePrefabs;
    }

}